package com.angel.utlis;

import net.sf.json.JSONObject;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * ip与物理地址转换工具
 *
 * @author Rabit
 */
public class GetIpUtli {

    /***
     * 获取真实的请求地址
     * @param request 请求的信息request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 火气请求的地址json
     *
     * @param ip ip地址
     * @param ak 百度ak
     * @return 请求结果
     */
    public String getAddress(String ip, String ak) {
        String url = "https://api.map.baidu.com/location/ip";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);
        params.add("ip", ip);
        params.add("ak", ak);
        params.add("coor", "bd09ll");
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        String msg = response.getBody();
        System.out.println("getAddress:==" + msg);
        return msg;
    }

    /**
     * 解析json
     *
     * @param json json 字符串
     * @return 最终解析地址
     */
    public String addJson(String json) {
        System.out.println("addJson:==" + json);
        Map map = null;
        try {
            map = JSONObject.fromObject(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int status = (int) map.get("status");
        if (0 != status) {
            return null;
        }
        if (map.containsKey("content")) {
            JSONObject jsonObject = (JSONObject) map.get("content");
            if (jsonObject.containsKey("address")) {
                return (String) jsonObject.get("address");
            }
        }
        return null;
    }

    public String getAdd(String ip, String ak) {
        String msg = this.getAddress(ip, ak);
        String addr = null;
        if (msg != null) {
            addr = addJson(msg);
        }
        return addr == null ? "无法解析地址" : addr;

    }


}
